from django.http import JsonResponse
from django.views import View
from rest_framework.generics import UpdateAPIView, ListAPIView, CreateAPIView
from rest_framework.response import Response

from question.utils import get_user_dict
from recruit.models import Enterprise
from recruit.serializers.enterprise import EnterpriseSearchHotlistSerializer, EenterpriseIdSerializer
from users.models import User


class EnterpriseIdVisitView(View):
    """增加企业访问次数"""

    def put(self, request, id):

        try:
            # 查询数据库
            enterprise = Enterprise.objects.get(id=id)
        except Exception as e:
            return JsonResponse({'message': '数据库查询错误', 'success': False})

        # 访问量+
        enterprise.visits += 1
        enterprise.save()

        return JsonResponse({"message": "更新成功", "success": True})


# 热门企业
class EnterpriseSearchHotlistView(ListAPIView):
    serializer_class = EnterpriseSearchHotlistSerializer
    queryset = Enterprise.objects.all().order_by('visits')[:4]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)

        data_dict = serializer.data

        for data in data_dict:
            logo = data['logo']
            # 修改logo地址
            data['logo'] = logo.replace('8000/enterprise/search/hotlist/', '8888/')

            # 获取企业对象
            enterprise = Enterprise.objects.get(id=data['id'])

            data['recruits'] = [enterprise.recruits.all().count()]

        return Response(data_dict)
        # return Response(serializer.data)


# 收藏公司
class EnterpriseIdCollectView(View):
    def post(self, request, id):
        # 获取用户信息
        user_dict = get_user_dict(request)

        # 判断用户是否合法
        if user_dict:
            # 获取用户
            user = User.objects.get(id=user_dict['user_id'])
        else:
            return JsonResponse({'message': '未登录', 'success': False})

        # 获取公司对象
        try:
            enterprise = Enterprise.objects.get(id=id)
        except Exception as e:
            return JsonResponse({'message': '数据库错误', 'success': False})

        # 添加数据
        users = enterprise.users.all()
        count = users.count()

        # 用户是否收藏
        if user in users:
            # 取消收藏
            enterprise.users.remove(user)
            count -= 1
        else:
            # 收藏
            enterprise.users.add(user)
            count += 1

        return JsonResponse({'message': 'ok', 'success': True})


# 企业详情
class EenterpriseIdView(ListAPIView):
    serializer_class = EenterpriseIdSerializer

    def get_queryset(self):
        # 获取查询条件
        id = self.kwargs.get('id', None)

        if not id:
            return Enterprise.objects.all()

        return Enterprise.objects.filter(id=id)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)

        data_dict = serializer.data[0]
        # 获取企业对象
        enterprise = Enterprise.objects.get(id=data_dict["id"])

        # 设置人数
        count = enterprise.users.all().count()
        data_dict['users'] = [count]

        logo = data_dict['logo']
        logo = logo.replace(f'8000/enterprise/{data_dict["id"]}/', '8888/')
        data_dict['logo'] = logo

        # # 渲染数据
        # recruits = data_dict['enterprise']['recruits']
        # for i in recruits:
        #     # 修改数据
        #     i['enterprise']['recruits'] = [enterprise.recruits.all().count()]
        #     logo = i['enterprise']['logo']
        #     logo = logo.replace(f'8000/recruits/{data_dict["id"]}/', '8888/')
        #     i['enterprise']['logo'] = logo

        # 返回响应
        return Response(data_dict)
